package org.lee.tpl.app;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * HttpClient
 *
 * @author dralee
 * @date 2021-11-24 13:41:19
 **/
@Slf4j
public class HttpClient {
    public static String doGet(String url) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String content = null;
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            // 超时15000毫秒
            connection.setConnectTimeout(15000);
            // 读取数据超时60000ms
            connection.setReadTimeout(60000);
            connection.connect();
            // 成功请示
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                StringBuilder sb = new StringBuilder(128);
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\r\n");
                }
                content = sb.toString();
            }
        } catch (MalformedURLException e) {
            log.error("doGet error: {}", e);
        } catch (IOException e) {
            log.error("doGet error: {}", e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error("doGet close br error: {}", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("doGet close is error: {}", e);
                }
            }
            assert connection != null;
            connection.disconnect();
        }
        return content;
    }
}
